package com.chensi.admin.web.controller;

import com.chensi.admin.web.common.Constants;
import com.chensi.admin.web.common.JsonResult;
import com.chensi.admin.web.controller.api.WebRoleApi;
import com.chensi.admin.web.domain.WebRole;
import com.chensi.admin.web.dto.WebRoleDTO;
import com.chensi.admin.web.dto.search.SearchWebRoleDTO;
import com.chensi.admin.web.exception.BaseException;
import com.chensi.admin.web.service.WebRoleService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.http.ResponseEntity;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import javax.validation.Valid;
import javax.validation.constraints.NotBlank;
import java.util.List;

/**
 * @date 2019/6/21 9:31
 */

@RestController
public class WebRoleController implements WebRoleApi {

    private final WebRoleService webRoleService;

    @Autowired
    public WebRoleController(WebRoleService webRoleService) {
        this.webRoleService = webRoleService;
    }

    @Override
    @DeleteMapping("/{id}")
    public ResponseEntity<JsonResult> delete(
            @NotBlank(message = "id不能为空") @PathVariable("id") String id) throws BaseException {
        webRoleService.delete(id);
        return ResponseEntity.ok(JsonResult.ok());
    }

    @Override
    @PutMapping("/{id}")
    public ResponseEntity<JsonResult> update(
            @NotBlank(message = "id不能为空") @PathVariable("id") String id
            , @Validated(Constants.Update.class) @RequestBody WebRole webRole) throws BaseException {
        webRoleService.update(webRole);
        return ResponseEntity.ok(JsonResult.ok());
    }

    @Override
    @GetMapping("/{id}")
    public ResponseEntity<JsonResult> get(
            @NotBlank(message = "id不能为空") @PathVariable("id") String id) throws BaseException {
        return ResponseEntity.ok(JsonResult.ok(webRoleService.get(id)));
    }

    @Override
    public ResponseEntity<JsonResult<List<WebRoleDTO>>> list() {
        return ResponseEntity.ok(
                JsonResult.ok(webRoleService.list())
        );
    }

    @Override
    public ResponseEntity<JsonResult<Page<WebRoleDTO>>> page(SearchWebRoleDTO searchWebRoleDTO) {
        return ResponseEntity.ok(
                JsonResult.ok(
                        webRoleService.page(
                                searchWebRoleDTO.getName()
                                , searchWebRoleDTO.getPageNum()
                                , searchWebRoleDTO.getPageSize()
                        )
                )
        );
    }

    @Override
    public ResponseEntity<JsonResult> save(@Valid @RequestBody WebRole webRole) throws BaseException {
        return ResponseEntity.ok(JsonResult.ok(webRoleService.create(webRole)));
    }
}
